import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/dialog/filter_dialog/filter_utils.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_plans_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_field_parameter_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class TaskEmergencyPlanController extends GetxController {
  /// 筛选右侧栏控制Key
  final popRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 搜索使用key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 搜索字符串
  String? search;

  /// 筛选列表
  List<FilterBean> allFilterList = [];

  /// 筛选字段数据
  List<FilterFieldParameterBean> fieldParameterList = [];

  /// 筛选字段请求数据
  Map<String, dynamic> filterMap = {};

  /// 当前执行节点
  ProcessNodesEntity implementNode = ProcessNodesEntity();

  /// 下一个执行节点
  ProcessNodesEntity nextNode = ProcessNodesEntity();

  /// 是否为结束节点的前一个节点
  bool last = false;

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  /// 初始化数据
  Future<void> initData() async {
    // 添加筛选列表
    fieldParameterList = [
      FilterFieldParameterBean(
        screenName: '预案类别',
        parameterName: 'planType',
        dictionaryType: 'yalb_Uh1UBbJr',
      ),
      FilterFieldParameterBean(
        screenName: '预案等级',
        parameterName: 'emergencyPlanLevel',
        dictionaryType: 'yadj_rg4LaK36',
      ),
    ];
    // 获取字典筛选列表
    allFilterList = await FilterUtils.getDictFilterList(fieldParameterList: fieldParameterList);
    update();
  }

  /// 获取列表数据
  Future<List<EmergencyPlansEntity>> getListData(int pageNum, int pageSize) async {
    filterMap.clear();
    final Map<String, dynamic> queryParameters = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'emergencyPlanName': search,
      // 固定审批状态为待审批
      'emergencyPlanStatus': 2,
    };
    // 获取筛选处参数
    for (var item in fieldParameterList) {
      if (item.parameterValue != null) {
        filterMap[item.parameterName] = item.parameterValue;
      }
    }
    queryParameters.addAll(filterMap);
    // 获取列表接口
    final res = await HttpUtil()
        .generateGetRequest<List<EmergencyPlansEntity>>(
          Interface.getExecutableList,
          queryParameters: queryParameters,
        )
        .execute();
    List<EmergencyPlansEntity>? data;
    res.onSuccess((result) {
      if (result.data != null) {
        data = result.data!;
      }
    });
    return data ?? [];
  }

  /// 筛选
  void screen() {
    popRightScaffoldKey.currentState?.openEndDrawer();
  }

  /// 筛选确认
  void screenConfirm(List<FilterBean> value) {
    allFilterList = value;
    // 参数清空
    for (var item in fieldParameterList) {
      item.parameterValue = null;
    }
    for (var i in value) {
      if (i.chosenValue.isEmpty) {
        continue;
      }
      // 获取标题相同的参数实体
      final result = fieldParameterList.firstWhere((data) => data.screenName == i.title);
      // 单选所以选中第一个就可以
      result.parameterValue = i.chosenValue[0].value;
    }
    update();
    refreshPage();
  }

  /// 点击审批按钮
  Future<void> clickOnApproval(EmergencyPlansEntity item) async {
    //获取数据
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getProcessNodesByBusinessId,
        queryParameters: {'processEncoding': item.processEncoding, 'businessId': item.id}).execute(isShowLoading: true);
    //查询到流程节点数据
    res.onSuccess((result) async {
      if (result.data!.isNotEmpty) {
        final List<ProcessNodesEntity> nodeList = result.data!;
        for (int i = 0; i < nodeList.length; i++) {
          final node = nodeList[i];
          //找到当前执行节点
          if (node.executableOrNot == 1) {
            // 点击项的执行节点
            implementNode = node;
            try {
              // 是否为结束节点的前一个节点
              last = (i == nodeList.length - 2);
              // 如果不为最后一个节点,设置下一个节点数据
              if (!last) {
                nextNode = nodeList[i + 1];
              }
              // switch (node.appRoutingAddress) {
              //   // 审批-进入审批页面
              //   case '/approval':
              //     Get.toNamed(AppRoutes.emergencyPlanApproval, arguments: item.id);
              //     break;
              // }
              // 只有审批节点会显示
              Get.toNamed(AppRoutes.emergencyPlanApproval, arguments: item.id);
              break;
            } catch (e) {
              AppToast.showWarning('当前审批流程节点数据异常!');
              break;
            }
          }
        }
      } else {
        AppToast.showWarning('数据异常,未查询到流程数据!');
      }
    });
  }

  /// 搜索
  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }
}
